package com.example.demo.config.jdbc;

import cn.hutool.core.collection.CollUtil;
import com.xphsc.easyjdbc.EasyJdbcTemplate;
import com.xphsc.easyjdbc.builder.SQL;
import com.xphsc.easyjdbc.core.exception.JdbcDataException;
import com.xphsc.easyjdbc.util.Assert;

import javax.sql.DataSource;
import java.util.List;

public class MyEasyJdbcTemplate extends EasyJdbcTemplate {

    public MyEasyJdbcTemplate(DataSource dataSource) {
        this.setDataSource(dataSource);
        this.useLocalCache(false);
        this.setDialectName("mysql");
        ;
        this.showSQL(true);
        this.afterPropertiesSet();
    }

    public int insert(String insertSql, Object... parameters) throws JdbcDataException {
        Assert.hasText(insertSql.toString(), "The SQL constructor cannot be empty");
        int rows = super.getJdbcBuilder().update(insertSql, parameters);
        return rows;
    }

    public int update(SQL updateSql, Object... parameters) throws JdbcDataException {
        Assert.notNull(updateSql, "The SQL constructor cannot be empty");
        int rows = this.getJdbcBuilder().update(updateSql.toString(), parameters);
        return rows;
    }

    @Override
    public <T> T get(String sql, Class<?> persistentClass, Object... parameters) throws JdbcDataException {
        Assert.notNull(persistentClass, "Entity type cannot be empty");
        List<T> results = find(sql, persistentClass, parameters);
        if (CollUtil.isNotEmpty(results)) {

            return results.get(0);
        }
        return null;
    }

    public int delete(String deleteSql, Object... parameters) throws JdbcDataException {
        Assert.hasText(deleteSql.toString(), "The SQL constructor cannot be empty");
        int rows = this.getJdbcBuilder().update(deleteSql.toString(), parameters);
        return rows;
    }
}
